/**
 * @copyright 2015 Indie Semiconductor.
 *
 * This file is proprietary to Indie Semiconductor.
 * All rights reserved. Reproduction or distribution, in whole
 * or in part, is forbidden except by express written permission
 * of Indie Semiconductor.
 *
 * @file flash_device.c
 */

#include <stdint.h>
#include <string.h>
#include "flash_device.h"
#include "flash_sfrs.h"


uint8_t flashBuff[FLASH_SECTOR_SIZE];

// address + size can't overlap section address
int32_t Flash_devCopyToFlash(uint8_t *const buff, uint32_t address, uint16_t size)
{
    uint32_t temp;
    uint32_t offsetAddr;
    uint32_t sectorAddr;
    if ( (address < PARAMS_STORAGE_ADDRESS_START) || (address + size) >= FLASH_FINAL_ADDRESS ||  size == 0 || ((address%FLASH_SECTOR_SIZE) + size) > FLASH_SECTOR_SIZE){
        return -1;
    }
    sectorAddr = (address/FLASH_SECTOR_SIZE)*FLASH_SECTOR_SIZE;
    offsetAddr = address%FLASH_SECTOR_SIZE;
    memcpy((uint32_t*)flashBuff, (uint32_t *)sectorAddr, FLASH_SECTOR_SIZE);
    for (uint16_t i = 0; i < size; i++){
        flashBuff[offsetAddr+i] = buff[i];
    }
    // Erase sector data
    f_FLASH_EraseSector(sectorAddr);
    // Write data to flash
    for (uint32_t i = 0; i < FLASH_SECTOR_SIZE/4; i++){
        temp = *((uint32_t *)flashBuff + i);
        f_FLASH_WriteWord(sectorAddr + (i << 2), temp);
    }
    return 0;
}
